package com.lujieni.springboothutool.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import com.lujieni.springboothutool.convert.CaptchaConvert;
import com.lujieni.springboothutool.vo.CaptchaImageRespVO;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequiredArgsConstructor
public class CaptchaController {

    private final RedisTemplate<String, String> redisTemplate;

    private static final String captchaPrefix = "captcha_code:%s";

    /**
     * 获取验证码
     * CircleCaptcha无法直接返回给前端因为当中包含BufferedImage对象（无法JSON序列化） OutputStream流对象!!!
     */
    @GetMapping("/get/captcha")
    public CaptchaImageRespVO getCaptcha(){
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 30);
        String uuid = IdUtil.fastSimpleUUID();
        String code = circleCaptcha.getCode();
        redisTemplate.opsForValue().set(String.format(captchaPrefix, uuid), code, 30, TimeUnit.MINUTES);
        String base64 = "data:image/png;base64,"+circleCaptcha.getImageBase64();
        CaptchaImageRespVO result = CaptchaConvert.INSTANCE.convert(base64, uuid);
        return result;
    }

    /**
     * 获取验证码
     */
    @GetMapping("/checkCaptcha")
    public Boolean checkCaptcha(String uuid, String code){
        String captchaCode = redisTemplate.opsForValue().get(String.format(captchaPrefix, uuid));
        if(Objects.equals(captchaCode, code)){
            redisTemplate.delete(String.format(captchaPrefix, uuid));
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}
